// 歌词处理逻辑
import { useStore } from 'vuex'
import { computed, watch, ref } from 'vue'
import { getLyric } from '../../service/song'
import Lyric from 'lyric-parser'
export default function useLyric({ songReady, currentTime }) {
  const currentLyric = ref(null) // 歌词
  const store = useStore()
  const pureMusicLyric = ref(0) // 没有歌词的情况显示
  const playingLyric = ref('') // 当前播放的歌词 单行歌词显示
  const currentLineNum = ref(0)// 当前显示的行号
  const lyricScrollRef = ref(null) // 滚动Dom
  const lyricListRef = ref(null) // 歌词Dom
  const currentSong = computed(() => store.getters.currentSong) // 获取当前播放的歌曲
  watch(currentSong, async (newSong) => { // 切换歌曲的时候发送请求获取歌词
    if (!newSong.url || !newSong.id) { // 歌曲不合法
      return
    }// 切换歌曲会有bug 需要停止播放歌词 歌词会和歌曲不同步
    stopLyric() // 停止
    currentLyric.value = null // 清空上首歌曲的歌词
    currentLineNum.value = 0 // 歌词下标0
    pureMusicLyric.value = ''
    playingLyric.value = ''
    const lyric = await getLyric(newSong) // 异步
    store.commit('addSangLyric', { song: newSong, lyric })// 给当前歌曲添加歌词
    if (currentSong.value.lyric !== lyric) {
      // debugger// 如果切换歌曲下面操作取消 因为获取歌词是异步的，最新的歌词为准
      return
     }
    currentLyric.value = new Lyric(lyric, handleLyric) // 参数1字符串 2函数
    const hasLyric = currentLyric.value.lines.length
    if (hasLyric) { // 判断是否有歌词
      if (songReady.value) {
        playLyric()
      }
    } else { // 没有歌词
      playingLyric.value = pureMusicLyric.value = lyric.replace(/\[(\d{2}):(\d{2}):(\d{2})\]/g, '')
    }
  })
  function playLyric() { // 播放歌词 与歌曲做同步
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      currentLyricVal.seek(currentTime.value * 1000) // 播放歌词和歌曲同步
    }
  }
  function stopLyric() { // 暂停歌词
    const currentLyricVal = currentLyric.value
    if (currentLyricVal) {
      currentLyricVal.stop() // 歌词停止播放
    }
  }
  function handleLyric({ lineNum, txt }) { // 每一行歌词播放时候会触发函数
    currentLineNum.value = lineNum // 歌词列表的下标
    playingLyric.value = txt // 当前播放的歌词
    // console.log(lineNum)
    const scrollComp = lyricScrollRef.value
    const listEl = lyricListRef.value
    if (!listEl) {
      return
    }
    if (lineNum > 5) { // 歌词大于5条的时候
      const lineEl = listEl.children[lineNum - 5]
      // console.log(listEl.children[1])
      scrollComp.scroll.scrollToElement(lineEl, 1000) // 1秒钟
    } else {
      scrollComp.scroll.scrollTo(0, 0, 1000) // 滚动到顶部
    }
  }
  return {
    currentLyric,
    currentLineNum,
    playLyric,
    lyricScrollRef,
    lyricListRef,
    stopLyric,
    pureMusicLyric,
    playingLyric
  }
}
